package com.ruoyi.imports.service.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.imports.domain.*;
import com.ruoyi.imports.mapper.TdProductionMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.imports.mapper.TdProductionConsumeMapper;
import com.ruoyi.imports.service.ITdProductionConsumeService;

/**
 * 药剂消耗明细Service业务层处理
 *
 * @author ruoyi
 * @date 2025-07-19
 */
@Service
public class TdProductionConsumeServiceImpl implements ITdProductionConsumeService {
    @Autowired
    private TdProductionConsumeMapper tdProductionConsumeMapper;

    @Autowired
    private TdProductionMapper tdProductionMapper;

    /**
     * 查询药剂消耗明细
     *
     * @param id 药剂消耗明细主键
     * @return 药剂消耗明细
     */
    @Override
    public TdProductionConsume selectTdProductionConsumeById(Long id) {
        return tdProductionConsumeMapper.selectTdProductionConsumeById(id);
    }

    /**
     * 查询药剂消耗明细列表
     *
     * @param tdProductionConsume 药剂消耗明细
     * @return 药剂消耗明细
     */
    @Override
    public List<TdProductionConsume> selectTdProductionConsumeList(TdProductionConsume tdProductionConsume) {
        return tdProductionConsumeMapper.selectTdProductionConsumeList(tdProductionConsume);
    }

    /**
     * 新增药剂消耗明细
     *
     * @param tdProductionConsume 药剂消耗明细
     * @return 结果
     */
    @Override
    public int insertTdProductionConsume(TdProductionConsume tdProductionConsume) {
        tdProductionConsume.setCreateTime(DateUtils.getNowDate());
        return tdProductionConsumeMapper.insertTdProductionConsume(tdProductionConsume);
    }

    /**
     * 修改药剂消耗明细
     *
     * @param tdProductionConsume 药剂消耗明细
     * @return 结果
     */
    @Override
    public int updateTdProductionConsume(TdProductionConsume tdProductionConsume) {
        tdProductionConsume.setUpdateTime(DateUtils.getNowDate());
        return tdProductionConsumeMapper.updateTdProductionConsume(tdProductionConsume);
    }

    /**
     * 批量删除药剂消耗明细
     *
     * @param ids 需要删除的药剂消耗明细主键
     * @return 结果
     */
    @Override
    public int deleteTdProductionConsumeByIds(Long[] ids) {
        return tdProductionConsumeMapper.deleteTdProductionConsumeByIds(ids);
    }

    /**
     * 删除药剂消耗明细信息
     *
     * @param id 药剂消耗明细主键
     * @return 结果
     */
    @Override
    public int deleteTdProductionConsumeById(Long id) {
        return tdProductionConsumeMapper.deleteTdProductionConsumeById(id);
    }

    @Override
    public void importOperatingDataType(List<ProductionExcelData> excelDataList, Long projectId) {
        // 1. 基础校验
        if (excelDataList == null || excelDataList.isEmpty()) {
            throw new IllegalArgumentException("导入数据不能为空");
        }

        // 存储Excel行索引与主表ID的映射（用于关联子表）
        HashMap<Integer, Long> productionToMainMap = new HashMap<>(excelDataList.size());
        try {
            //处理主表
            for (int i = 0; i < excelDataList.size(); i++) {
                ProductionExcelData productionExcelData = excelDataList.get(i);
                TdProduction tdProduction = buildMainData(productionExcelData, projectId);
                tdProductionMapper.insertTdProduction(tdProduction);
                productionToMainMap.put(i, tdProduction.getId());
            }
            List<TdProductionConsume> typeDataList = new ArrayList<>();
            for (int i = 0; i < excelDataList.size(); i++) {
                ProductionExcelData productionExcelData = excelDataList.get(i);
                Long mainId = productionToMainMap.get(i);
                typeDataList.add(buildTypeData(productionExcelData, mainId));
            }
// 批量插入子表
            if (!typeDataList.isEmpty()) {
                tdProductionConsumeMapper.batchInsert(typeDataList);
            }

        } catch (Exception e) {
            // 异常捕获与日志
            throw new RuntimeException("导入失败：" + e.getMessage(), e);
        }


    }

    private TdProductionConsume buildTypeData(ProductionExcelData productionExcelData, Long mainId) {
        TdProductionConsume tdProductionConsume = new TdProductionConsume();
        tdProductionConsume.setMainId(mainId);
        // 生化药剂相关字段映射
        tdProductionConsume.setSodiumDihydrogenPhosphate(productionExcelData.getSodiumDihydrogenPhosphate());
        tdProductionConsume.setGlucose(productionExcelData.getGlucose());
        tdProductionConsume.setBioActivePhosphorus(productionExcelData.getBioActivePhosphorus());
        tdProductionConsume.setDefoamer(productionExcelData.getDefoamer());
        tdProductionConsume.setLiquidSodiumAcetate(productionExcelData.getLiquidSodiumAcetate());
        tdProductionConsume.setCompositeCarbonSource(productionExcelData.getCompositeCarbonSource());
        tdProductionConsume.setCompositeAlkali(productionExcelData.getCompositeAlkali());
        tdProductionConsume.setFerrousSulfate(productionExcelData.getFerrousSulfate());
        tdProductionConsume.setLiquidAlkali(productionExcelData.getLiquidAlkali());
        tdProductionConsume.setSodaAsh(productionExcelData.getSodaAsh());

// 后混凝深度处理药剂相关字段映射
        tdProductionConsume.setDs821(productionExcelData.getDs821());
        tdProductionConsume.setDs882(productionExcelData.getDs882());
        tdProductionConsume.setSodiumHypochlorite(productionExcelData.getSodiumHypochlorite());
        tdProductionConsume.setDs6031Liquid(productionExcelData.getDs6031Liquid());
        tdProductionConsume.setDs6031Solid(productionExcelData.getDs6031Solid());
        tdProductionConsume.setDs832(productionExcelData.getDs832());
        tdProductionConsume.setDs7021(productionExcelData.getDs7021());
        tdProductionConsume.setDs8031(productionExcelData.getDs8031());
        tdProductionConsume.setSulfuricAcid(productionExcelData.getSulfuricAcid());
        tdProductionConsume.setDs722(productionExcelData.getDs722());
        tdProductionConsume.setLiquidAlkali32pct(productionExcelData.getLiquidAlkali32pct());
        tdProductionConsume.setLiquidAlkali10pct(productionExcelData.getLiquidAlkali10pct());
        tdProductionConsume.setFlakeAlkali(productionExcelData.getFlakeAlkali());

// 中水药剂相关字段映射
        tdProductionConsume.setLowPhosphorusScaleInhibitor(productionExcelData.getLowPhosphorusScaleInhibitor());
        tdProductionConsume.setCitricAcid(productionExcelData.getCitricAcid());
        tdProductionConsume.setHydratedLime(productionExcelData.getHydratedLime());
        tdProductionConsume.setQuicklime(productionExcelData.getQuicklime());
        tdProductionConsume.setWheatBran(productionExcelData.getWheatBran());
        tdProductionConsume.setNonOxidizingBiocide(productionExcelData.getNonOxidizingBiocide());
        tdProductionConsume.setReducingAgent(productionExcelData.getReducingAgent());
        tdProductionConsume.setEdtaTetrasodium(productionExcelData.getEdtaTetrasodium());
        tdProductionConsume.setHydrochloricAcid(productionExcelData.getHydrochloricAcid());


        return tdProductionConsume;
    }

    private TdProduction buildMainData(ProductionExcelData productionExcelData, Long projectId) throws ParseException {
        TdProduction mainData = new TdProduction();
        mainData.setProjectId(projectId);

        //校验日期和时间非空
        String date = productionExcelData.getDate();

        if (date == null) {
            throw new IllegalArgumentException("日期或时间不能为空");
        }
        // 合并日期时间字符串（格式：yyyy年M月d日）
        String dateTimeStr = date.trim();

        // 解析为Date（仅保留必要格式，适配Excel实际格式）
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年M月d日", Locale.CHINESE);
        sdf.setLenient(false); // 严格校验格式
        Date recordTime = sdf.parse(dateTimeStr);
        mainData.setRecordDate(recordTime);

        mainData.setWaterTreatment(productionExcelData.getChuLiFeiShui());
        mainData.setLaborCost(productionExcelData.getRenGongFeiYong());
        mainData.setMaintenanceCost(productionExcelData.getWeiXiuFeiYong());
        mainData.setOtherCost(productionExcelData.getQiTaFeiYong());
        mainData.setReagentCost(productionExcelData.getYaoJiFeiYong());
        mainData.setDailyProfit(productionExcelData.getRiLiRun());
        mainData.setLargeExpenseNote(productionExcelData.getDaEFeiYong());
        mainData.setAbnormalStatus(productionExcelData.getShengChanYiChang());
        mainData.setCreateTime(new Date());
        mainData.setUpdateTime(new Date());

        return mainData;
    }
}
